iT邦幫忙

2024 iThome 鐵人賽

DAY 11
0

You are given a 0-indexed 2D array grid of size 2 x n, where grid[r][c] represents the number of points at position (r, c) on the matrix. Two robots are playing a game on this matrix.

Both robots initially start at (0, 0) and want to reach (1, n-1). Each robot may only move to the right ((r, c) to (r, c + 1)) or down ((r, c) to (r + 1, c)).

At the start of the game, the first robot moves from (0, 0) to (1, n-1), collecting all the points from the cells on its path. For all cells (r, c) traversed on the path, grid[r][c] is set to 0. Then, the second robot moves from (0, 0) to (1, n-1), collecting the points on its path. Note that their paths may intersect with one another.

The first robot wants to minimize the number of points collected by the second robot. In contrast, the second robot wants to maximize the number of points it collects. If both robots play optimally, return the number of points collected by the second robot.


這次題目真的長到不行,光是題目長度我就覺得這題不簡單。
題目大意就是有一個2*n的矩陣跟兩個機器人,機器人會從矩陣左上出發到右下(只能往右、往下移動)。
第一個機器人收集走過的地方的數值,且那個地方會變成0;他的目標是餘留最少的數值給第二個機器人。
第二個機器人的目標是收集剩餘最多的數。
我們需要返回第二個機器人能收集到的點數。
個人解題思路是:
0. 因為路徑只能往下,所以可以遍歷每個轉彎點,計算出最大的和的那條路給一號機器人走。

  1. 遍歷每個轉彎點
  2. 對每個轉彎點,計算二號走另一條路所得
  3. 找到最少所得然後返回

class Solution {
public int gridGame(int[][] grid) {
int n = grid[0].length;
int minPoints = Integer.MAX_VALUE;
// 遍歷每一個可能的轉向點
for (int i = 0; i < n; i++) {
// 第一個機器人走到 (0, i) 往下轉彎
int[][] tempGrid = copyGrid(grid);
// 第一個機器人走過的路徑,將其點數設為0
for (int j = 0; j <= i; j++) {
tempGrid[0][j] = 0; // 上面行的前 i 列
}
for (int j = i; j < n; j++) {
tempGrid[1][j] = 0; // 下面行的後 i 列
}
// 選擇從剩下的路徑中得分最大的
int secondRobot = Math.max(sumRow(tempGrid[0]), sumRow(tempGrid[1]));
minPoints = Math.min(minPoints, secondRobot);
}
return minPoints;
}
// 複製grid的,才不會覆蓋原本的值
private int[][] copyGrid(int[][] grid) {
int[][] newGrid = new int[2][grid[0].length];
for (int i = 0; i < 2; i++) {
for (int j = 0; j < grid[0].length; j++) {
newGrid[i][j] = grid[i][j];
}
}
return newGrid;
}
// 計算某一行的點數和
private int sumRow(int[] row) {
int sum = 0;
for (int points : row) {
sum += points;
}
return sum;
}
}


這次遇到的問題是我忽略再輸入一次會重新填寫原本的grid,所以一直失敗...
後來借助chatgpt之力才發現這個漏洞。

總之丟去leetcode!快樂結束這回合,明天見!
https://ithelp.ithome.com.tw/upload/images/20240926/20169432DwBg11KBc9.png


上一篇
day-10[easy.2016]maximum difference between increasing elements
下一篇
day-12[medium.2007]find original array from doubled array
系列文
轉生理工組後從零開始的leetcode刷題12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言